package com.sky.handler;
import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;

import org.springframework.web.bind.MethodArgumentNotValidException;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.validation.ConstraintViolationException;
import java.sql.SQLIntegrityConstraintViolationException;

import java.util.stream.Collectors;
/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        return Result.error(ex.getMessage());
    }
    /**
     * 处理sql异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")) {
            String[] split = message.split(" ");
            String username = split[2] ;
            String msg  = username+ MessageConstant.REPEAT_KEY;
            return Result.error(msg);
        } else {
            log.info(message);
            return Result.error(MessageConstant.SQL_ERR);
        }
    }
    /**
     * 处理参数校验异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(MethodArgumentNotValidException ex) {
        String msg = ex.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(error -> error.getField() + "：" + error.getDefaultMessage())
                .collect(Collectors.joining("; "));
        return Result.error(msg);
    }
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public Result handleTypeMismatchException(MethodArgumentTypeMismatchException ex) {
        return Result.error("参数类型错误！");
    }
    @ExceptionHandler(ConstraintViolationException.class)
    public Result<?> handleValidationException(ConstraintViolationException ex) {
        String message = ex.getConstraintViolations().iterator().next().getMessage();
        return Result.error(message);
    }
//    // 处理空指针异常
//    @ExceptionHandler(NullPointerException.class)
//    public Result<String> handleNullPointerException(NullPointerException e) {
//        return Result.error("服务器发生空指针异常，请联系管理员");
//    }
//    // 捕获所有运行时异常
//    @ExceptionHandler(RuntimeException.class)
//    public Result<String> handleRuntimeException(RuntimeException e) {
//        return Result.error("服务器运行异常：" + e.getMessage());
//    }

    // 捕获所有异常，作为兜底
//    @ExceptionHandler(Exception.class)
//    public Result<String> handleException(Exception e) {
//        return Result.error("系统异常，请稍后重试");
//    }
}
